<template>
  <view v-if="currentStep != 'health-code'"
    class="bg-gradient-to-br from-[#4caf50] to-[#2e7d32] text-white p-[60rpx_40rpx_60rpx] text-center relative">
    <!-- <view class="text-[48rpx] font-bold flex items-center justify-center mb-[20rpx]">
      <IconFont name="heartbeat" class="mr-[20rpx] text-[56rpx]" />
      <text>健康中国</text>
    </view> -->
    <text class="text-[40rpx] mb-[40rpx] block">电子健康卡申请</text>
    <StepProgress
      :progressWidth="progressWidth"
      :step2Active="true"
      :step3Active="true"
      :handleCreateContract="handleCreateContract"
    />
  </view>
  <view class="min-h-[800rpx]">
    <StepHealthCode
      v-if="currentStep === 'health-code'"
      :code="code"
      :user="formData"
      @reapply="reapply"
    />
    <StepStartSign
      v-else-if="currentStep === 'start-sign'"
      :contractName="contractName"
      @sign="handleCreateContract"
    />
    <StepCompleteSign
      v-else-if="currentStep === 'complete-sign'"
      :status="status"
      :contractStatus="contractStatus"
      :contractName="contractName"
      @check="handleCheckAction"
    />
    <StepRegister
      v-else-if="currentStep === 'register'"
      :formData="formData"
      @update:formData="val => formData = val"
      @submit="handleRegister"
    />
    <StepSuccess
      v-else-if="currentStep === 'success'"
      @showCode="currentStep = 'health-code'"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { User, Hospital } from './types'
import Taro from '@tarojs/taro'
import { request } from '@/service/request';
import { IconFont } from '@nutui/icons-vue-taro'
import { localStg } from '@/utils';
import { useAuthStore } from '@/store';
import { CONTENT_TYPE } from '@/constants/service'
import { getContractTemplateByName, createContract, getHealthCode, registerHealthCode } from './tooler'
import StepRegister from './component/StepRegister.vue'
import StepStartSign from './component/StepStartSign.vue'
import StepCompleteSign from './component/StepCompleteSign.vue'
import StepSuccess from './component/StepSuccess.vue'
import StepHealthCode from './component/StepHealthCode.vue'
import StepProgress from './component/StepProgress.vue'


const userStore = useAuthStore();
const currentStep = ref<'register' | 'start-sign' | 'complete-sign' | 'success' | 'health-code'>('')
const formData = ref<User>({
  name: userStore.nurseUser.name || '',
  idcard: userStore.nurseUser.idcard || '',
  phone: userStore.nurseUser.phone || '',
  vuid: userStore.nurseUser.vuid || ''
})
const code = ref('')
const hospital = ref<Hospital | null>(null)
const contractName = '健康码注册';
let templateData: any = null;
const status = ref('PENDING');


// 进度条等状态
const progressWidth = computed(() => {
  switch (currentStep.value) {
    case 'start-sign': return 0
    case 'complete-sign': return 50
    case 'register': return 80
    case 'success':
    case 'health-code': return 100
    default: return 0
  }
})

function reapply() {
  // currentStep.value = 'start-sign'
  // return;

  if (!Taro.getStorageSync(contractName)) {
    currentStep.value = 'start-sign'
    return;
  }

  // 如果合同时间存在，检查合同是否签署
  currentStep.value = 'complete-sign'

}


onMounted(async () => {
  if(!userStore.nurseUser.phone){
    Taro.showModal({
      title: '提示',
      content: '请先绑定手机号',
      showCancel: false,
      confirmText: '确定',
      success: function (res) {
        if (res.confirm) {
          Taro.navigateTo({ url: '/package-my/info/phone' })
        }
      }
    })
    return;
  }
  if(!userStore.nurseUser.idcard){
    Taro.showModal({
      title: '提示',
      content: '请先绑定身份证号',
      showCancel: false,
      confirmText: '确定',
      success: function (res) {
        if (res.confirm) {
          Taro.navigateTo({ url: '/package-my/info/idcard' })
        }
      }
    })
    return;
  }
  const str = Taro.getStorageSync('defaultHospital');
  hospital.value = str ? JSON.parse(str) : null;
  initHealthCode();
})

async function initHealthCode() {
  console.log("hospital", hospital.value)
  console.log("userStore", userStore.nurseUser)

  if (!hospital.value?.operatorid) {
    Taro.showToast({
      title: '请先设置医院负责人',
      icon: 'none',
      duration: 2000
    })
    return;
  }

  templateData = await getContractTemplateByName(hospital.value, contractName)

  if(!templateData){
    Taro.showToast({
      title: '未找到合同模板',
      icon: 'none',
      duration: 2000
    })
    return;
  }

  await request.post('/health_code/healthCode/getToken', {}, { useErrMsg: true})

  if(userStore.nurseUser.vuid){
    currentStep.value = 'health-code'
    code.value = await getHealthCode(userStore.nurseUser);
    return;
  }


  // 如果合同时间不存在，提示发起合同
  if (!Taro.getStorageSync(contractName)) {
    currentStep.value = 'start-sign'
    return;
  }

  // 如果合同时间存在，检查合同是否签署
  currentStep.value = 'complete-sign'

  const res = await checkContract();
  if (res) {
    currentStep.value = 'register'
  }
}

const contractStatus = ref('')


//检查合同是否签署
const checkContract = async () => {
  // /tencent_esign/tencent_flowstatuscallback/tencentFlowstatuscallbackInfo/queryById
  // /jeecg-boot/tencent_esign/tencent_contract/tencentContractInfo/list
  // tencent_esign/tencent_contract/tencentContractInfo/list
  const res:any = await request.get('/tencent_esign/tencent_flowstatuscallback/tencentFlowstatuscallbackInfo/list', {
    // "occurtime": Taro.getStorageSync(contractName + '_time'),
    // "approvenamea": userStore.nurseUser.name,
    // "proxyoperatoropenid": hospital.value?.operatorid,
    // "templateid": templateData?.templateId,
    // flowname: '健康码注册协议',
    // flowname: contractName,
    // pageSize: 100,

    // id: Taro.getStorageSync(contractName),
    flowid: Taro.getStorageSync(contractName),
  }, {
    useErrMsg: true
  })

  console.log("res==== checkContract", res)

  if(res.success?.records?.length){
    const records = res.success.records;
    records.forEach((item:any)=>{
      status.value = item.approvestatusa;
      contractStatus.value = item.conStatus
      console.log("contractStatus", contractStatus.value)
    })
    return status.value == 'ACCEPT';
  }
  return false;
}

function handleCheckAction() {
  checkContract().then((res) => {
    if (res) {
      currentStep.value = 'register';
      Taro.showToast({
        title: '电子合同签署成功！',
        icon: 'success',
        duration: 2000
      })
    }
    else {
      Taro.showToast({
        title: '电子合同未签署！',
        icon: 'none',
        duration: 2000
      })
    }
  })

}

// 注册健康卡
function handleRegister() {
  registerHealthCode(userStore.nurseUser as any).then((res: any) => {
    if (res) {
      code.value = res;
      currentStep.value = "health-code"
    }
    else {
      Taro.showToast({
        title: '注册失败',
        icon: 'none',
        duration: 2000
      })
    }
  })
  
}

function handleCreateContract() {
  createContract({
    hospital: hospital.value,
    user: userStore.nurseUser,
    templateId: templateData.templateId,
    flowName: "健康码注册协议",
    flowDescription: "健康码注册协议描述",
  }).then((res: any) => {
    console.log("res==== createContract", res)
    if (res.success) {
      currentStep.value = 'complete-sign'

      Taro.showToast({
        title: '电子合同已发送到您的手机，请及时签署！',
        icon: 'success',
        duration: 2000
      })
      Taro.setStorageSync(contractName, res.success);
    }
    else {
      Taro.showToast({
        title: res.message,
        icon: 'none',
        duration: 2000
      })
    }

  })

}
</script>